import { Dimensions, Pressable, StyleSheet, Text, View } from 'react-native'
import React, { useEffect, useState } from 'react'
import { Button } from '@ant-design/react-native'
import { ScrollView } from 'react-native-gesture-handler'
import { router, useFocusEffect } from 'expo-router'
import axios from 'axios'
import AsyncStorage from '@react-native-async-storage/async-storage'

export default function AddressPage() {
  const [data,setData]=useState([])
  const [address,setAddress]=useState({
    _id:'123'
  })
  useEffect(()=>{
    AsyncStorage.getItem('address').then((res:any)=>{
      setAddress(JSON.parse(res))
    })
  },[])
  const getlist=()=>{
    axios.get(`http://192.168.13.227:3000/czz/getAddress`)
    .then(res=>{
      setData(res.data.data)
    })
  }
  const delAddress=(_id:any)=>{
    axios.post(`http://192.168.13.227:3000/czz/delAddress`,{_id})
    .then(res=>{
      getlist()
    })
  }
  const selAddress=async(_id:any)=>{
    // await data.forEach((item:any)=>{
    //   if(item._id==_id){
    //     item.isdefault=true
    //     AsyncStorage.setItem('address',JSON.stringify(item))
    //   }else{
    //     item.isdefault=false
    //   }
    // })
    await axios.post(`http://192.168.13.227:3000/czz/updateAddress`,{_id:_id})
    .then(res=>{
      AsyncStorage.setItem('address',JSON.stringify(res.data.data))
      getlist()
      router.back()
    })
  }
  useFocusEffect(()=>{
    getlist()
  })
  return (
    <View style={{justifyContent:'center',alignItems:'center'}}>
      {
        data.map((item:any)=>(
          <Pressable key={item._id} onPress={()=>selAddress(item._id)}>
            <View style={item.isdefault?styles.Selected:styles.UnSelected}>
              <Text>{item.address}{item.fullAddress}</Text>
              <Text>{item.name} {item.phone}</Text>
              <Button type='warning' onPress={()=>delAddress(item._id)} style={{position:'absolute',right:10,top:10}}>删除</Button>
            </View>
          </Pressable>
        ))
      }
      <Button onPress={()=>router.push('/addAddress')} type='primary' style={{width:Dimensions.get('window').width*0.9,alignItems:'center',height:Dimensions.get('window').height*0.05,marginTop:5}}>添加新地址</Button>
    </View>
  )
}

const styles = StyleSheet.create({
  Selected:{
    borderColor:"red",
    width:Dimensions.get('window').width*0.9,alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderBottomColor:'#ccc',height:Dimensions.get('window').height*0.1,marginTop:10,backgroundColor:'#fff'
  },
  UnSelected:{
    width:Dimensions.get('window').width*0.9,alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderBottomColor:'#ccc',height:Dimensions.get('window').height*0.1,marginTop:10,backgroundColor:'#fff'
  }
})